import { NextApiRequest, NextApiResponse } from "next";

import { getConfigs } from "@/services";
import { Config } from "@/entities/Config";

async function getAppConfig(req: NextApiRequest, res: NextApiResponse<APIRes>) {
  const query = req.query ?? {};
  if (!query.appid) {
    // 缺少appid参数
    return res.status(400).json({
      success: false,
      data: {},
      message: "Missing appid parameter",
    });
  }

  //   console.log("🚀 ~ getAppConfig ~ query:", query);
  if (!query.env) {
    // 缺少env参数
    return res.status(400).json({
      success: false,
      data: {},
      message: "Missing env parameter",
    });
  }

  if (
    !["local", "development", "test", "production"].includes(
      query.env as string
    )
  ) {
    return res.status(400).json({
      success: false,
      data: {},
      message:
        "Invalid env parameter , avaliables: local, development, test, production",
    });
  }

  const appSecret = req.headers["x-app-secret"]; // header name will be convert to lowercase
  //   console.log("🚀 ~ getAppConfig ~ req.headers:", req.headers);
  if (!appSecret) {
    return res.status(400).json({
      success: false,
      data: {},
      message: "Missing X-APP-SECRET header",
    });
  }

  const env = query.env as string;
  req.query.env = "any"; // get all env configs
  req.query.disabled = "0"; // only fetch enabled configs

  const configsResult = await getConfigs(req);

  if (!configsResult.success) {
    return res.status(400).json(configsResult);
  }

  const configs = configsResult.data.configs;
  const commonConfigs = configs.filter((config) => config.env === "all");
  const envConfigs = configs.filter((config) => config.env === env);
  const mergedConfigs = commonConfigs.concat(envConfigs);
  const configData = {} as Obj;
  let value: any;
  mergedConfigs.forEach((config) => {
    const type = config.type;
    value = config.value;
    if (["json", "array", "object", "number"].includes(type)) {
      try {
        // if (type === 'array') {
        //   config
        // }
        value = JSON.parse(config.value);
      } catch (err) {
        console.log("========> JSON PARSE config.value error:", err);
        console.log("config:", config);
        console.log("config.value:", config.value);
        console.log("<======== JSON PARSE END");
      }
    }

    if (type === "boolean") {
      // @ts-ignore
      value = [true, "true", "1", 1, "True"].includes(config.value);
    }
    // console.log(
    //   config.name,
    //   "===========> config.type:",
    //   config.type,
    //   "===> value:",
    //   value
    // );
    configData[config.name] = value;
  });

  res.status(200).json({
    success: true,
    data: configData,
    message: "Get App config success",
  });
}

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse<APIRes>
) {
  if (req.method === "GET") {
    getAppConfig(req, res);
  } else {
    res
      .status(405)
      .json({ success: false, data: {}, message: "Method not allowed" });
  }
}
